package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("cezPayService")
public class CezPayServiceImpl extends BasePayment {




    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        return getCezPayUrl(userRecipientInfo,orderInfo);
    }

    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
        String token = cookieObj.getString("token");
        String ceztoken = cookieObj.getString("cezToken");
        String cardNo = cookieObj.getString("cardNo");
        String proxyIp =orderInfo.getProxyIp();
        headerMap.put("cookie",cookieObj.getString("cookie"));
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; U; CPU iPhone OS 10_3_3 like Mac OS X; en-us) AppleWebKit/603.3.8 (KtHTML, like Gecko) Mobile/7D11 scApp-ios-shihua/3.4.0 companyKey/874d8c821358a5e26f2524b10f43a292 lang/zh devId/idfv_22903ECD-DE80-4449-860E-37925D62BEC1 unionPay/3.1.1 devType/iPhone14,5 systemVersion/15.5");
        String url ="https://e.o2obest.cn/api/shihuaICWxRecharge/confirm";
        dataMap = new HashMap();
        dataMap.put("ajax","1");
        dataMap.put("cardNo",cardNo);
        dataMap.put("cezToken",ceztoken);
        dataMap.put("companyKey","874d8c821358a5e26f2524b10f43a292");
        dataMap.put("icPayType","3");
        dataMap.put("money", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        dataMap.put("ticket", "");
        dataMap.put("timeStamp", ""+System.currentTimeMillis()/1000);
        dataMap.put("token",token);
        dataMap.put("version","3.4.0");
        logger.info("预下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

        //headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+cookieObj.getString("userId"));
//        HttpResponse payHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"SYB下单",proxyIp);
        String payHttpResponse = HttpUtils.sendPostRequest(url,preStr,headerMap);
        logger.info("车e族请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(!payInforesultObj.getString("code").equals("00000")){
//            if()
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;
        }
        JSONObject order_info = payInforesultObj.getJSONObject("data");
        String orderSn = order_info.getString("orderSn");

        url ="https://e.o2obest.cn/api/shihuaICAliRecharge/pay?ajax=1&cezToken="+ceztoken+"&companyKey=874d8c821358a5e26f2524b10f43a292&orderSn="+orderSn+"&token="+token+"&version=3.4.0";
        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","CEZ","");
        logger.info("下单返回的:"+httpResponse.getBody());
        payInforesultObj = JSONObject.parseObject(httpResponse.getBody());
        JSONObject pay_info = payInforesultObj.getJSONObject("data");

        jsonObject.put("payUrl",pay_info.toJSONString());
        jsonObject.put("orderNo",orderSn);
        jsonObject.put("code","200");
        return jsonObject;
    }


    private JSONObject getCezPayUrl(TRecipientInfo userRecipientInfo,TOrderInfo orderInfo){
        JSONObject jsonObject = new JSONObject();
        //先查询数据库中该收款号下的已超时未支付的订单
        TOrderInfo queryOrder = new TOrderInfo();
        queryOrder.setRecipientId(userRecipientInfo.getId());
        queryOrder.setRealMoney(orderInfo.getRealMoney());
        queryOrder.setAliUserId(orderInfo.getAliUserId());
        queryOrder.setStatus(3);
        List<TOrderInfo> orderInfoList = orderInfoService.selectTOrderInfoList(queryOrder);
        if(orderInfoList.size()>0){
            logger.info("查询到超时未付款的订单，修改三方订单号====");
            TOrderInfo exitOrder = orderInfoList.get(0);
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            exitOrder.setPay3rdOrderNo(exitOrder.getPay3rdOrderNo().split("_")[0]+"_"+dateFormat.format(new Date()));
            exitOrder.setStatus(4);//已使用
            orderInfoService.updateTOrderInfo(exitOrder);
            JSONObject payInfo = JSONObject.parseObject(exitOrder.getQrcodeUrl());
            jsonObject.put("payUrl",exitOrder.getQrcodeUrl());
            jsonObject.put("orderNo",payInfo.getString("orderSn"));
            jsonObject.put("code","200");
            return jsonObject;
        }
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        String cookieStr = userRecipientInfo.getCookie();
        JSONObject cookieObj = JSONObject.parseObject(cookieStr);
        String token = cookieObj.getString("token");
        String ceztoken = cookieObj.getString("cezToken");
        String cardNo = cookieObj.getString("cardNo");
        String proxyIp =orderInfo.getProxyIp();
        headerMap.put("cookie",cookieObj.getString("cookie"));
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; U; CPU iPhone OS 10_3_3 like Mac OS X; en-us) AppleWebKit/603.3.8 (KtHTML, like Gecko) Mobile/7D11 scApp-ios-shihua/3.4.0 companyKey/874d8c821358a5e26f2524b10f43a292 lang/zh devId/idfv_22903ECD-DE80-4449-860E-37925D62BEC1 unionPay/3.1.1 devType/iPhone14,5 systemVersion/15.5");
        String url ="https://e.o2obest.cn/api/shihuaICAliRecharge/confirm";
        dataMap = new HashMap();
        dataMap.put("ajax","1");
        dataMap.put("cardNo",cardNo);
        dataMap.put("cezToken",ceztoken);
        dataMap.put("companyKey","874d8c821358a5e26f2524b10f43a292");
        dataMap.put("icPayType","3");
        dataMap.put("money", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        dataMap.put("ticket", "");
        dataMap.put("timeStamp", ""+System.currentTimeMillis()/1000);
        dataMap.put("token",token);
        dataMap.put("version","3.4.0");
        logger.info("预下单URL："+url);
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("请求参数："+preStr);

        //headerMap.put("Referer","https://www.shouyinbei.net/wap/merchant/h5pay?auth_code="+orderInfo.getAliAuthCode()+"&userAppId="+cookieObj.getString("userId"));
//        HttpResponse payHttpResponse = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"SYB下单",proxyIp);
        String payHttpResponse = HttpUtils.sendPostRequest(url,preStr,headerMap);
        logger.info("车e族请求返回的:"+payHttpResponse);

        JSONObject payInforesultObj = JSONObject.parseObject(payHttpResponse);
        if(!payInforesultObj.getString("code").equals("00000")){
            if(payInforesultObj.getString("code").equals("10001")){
//                CezLogin cezLogin = loginService;
                ResponseData responseData = loginService.cezlogin(userRecipientInfo);
                if(responseData.getSuccess()){
                    userRecipientInfo = userRecipientService.selectTRecipientInfoById(userRecipientInfo.getId());
                    return getCezPayUrl(userRecipientInfo,orderInfo);
                }
            }
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;
        }
        JSONObject order_info = payInforesultObj.getJSONObject("data");
        String orderSn = order_info.getString("orderSn");

        url ="https://e.o2obest.cn/api/shihuaICAliRecharge/pay?ajax=1&cezToken="+ceztoken+"&companyKey=874d8c821358a5e26f2524b10f43a292&orderSn="+orderSn+"&token="+token+"&version=3.4.0";
        HttpResponse httpResponse = HttpUtils.httpFormGet(url,headerMap,"","CEZ","");
        logger.info("下单返回的:"+httpResponse.getBody());
        payInforesultObj = JSONObject.parseObject(httpResponse.getBody());
        JSONObject pay_info = payInforesultObj.getJSONObject("data");
        userRecipientInfo.setTodayCount(userRecipientInfo.getTodayCount()+1);
        userRecipientService.updateTRecipientInfo(userRecipientInfo);
        jsonObject.put("payUrl",pay_info.toJSONString());
        jsonObject.put("orderNo",orderSn);
        jsonObject.put("code","200");
        return jsonObject;
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }

}
